
/**
 * @file        singleton.h
 * @author      OuYang
 * @date        2025/05/07
*/

#ifndef SINGLETON_H
#define SINGLETON_H

#include "global.h"

template <typename T>
class Singleton {
protected:
    // 默认构造
    Singleton() = default;

    // 删除拷贝构造
    Singleton(const Singleton<T>&) = delete;

    // 删除拷贝赋值
    Singleton& operator = (const Singleton<T>&) = delete;

    // 智能指针指向单例对象
    static std::shared_ptr<T> _instance;

public:
    // 获取单例智能指针
    static std::shared_ptr<T> GetInstance() {

        // 保证调用一次, C++ 11 之后static变量是线程安全的，所以这里是多余的
        static std::once_flag s_flag;
        std::call_once(s_flag, [&](){
            // 为什么这里不用shared_make??
            _instance = std::shared_ptr<T>(new T);

        });
        return _instance;
    }

    void PrintAddress() {
        std::cout << _instance.get() << std::endl;
    }

    ~Singleton() {
        std::cout << "this is singleton destruct" << std::endl;
    }
};

template <typename T>
std::shared_ptr<T> Singleton<T>::_instance = nullptr;


#endif // SINGLETON_H
